import { Checkbox, Row, Col, Divider, message, Select, Form } from "antd";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { useModel } from "umi";
import { AllMembers, FindOneRole, AllStaff, AllBusinessRoleMembers } from "../../_graphql/business_roles";
import { Button } from "@douyinfe/semi-ui";

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
const tailLayout = { wrapperCol: { offset: 6, span: 16 } };

const SetRoleMembers = ({ application, roleKey, role, reloadData }) => {
    const { graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        members: [],
        selectedMembers: [],
        selectedLevel: 1,
    });

    const loadMembers = async () => {
        let res;
        if (role.source === "organzation_staff") {
            res = await graphqlFetch({ query: AllStaff, variables: {} });
        } else {
            res = await graphqlFetch({ query: AllMembers, variables: {} });
        }
        let roleMembers = await graphqlFetch({
            query: AllBusinessRoleMembers,
            variables: {
                aiUuid: application?.aiUuid,
            },
        });
        if (roleMembers?.a?.nodes)
            state.members = res?.a?.nodes?.filter((item) => roleMembers.a.nodes.findIndex((_item) => _item.omUuid === item.omUuid) === -1) || [];
    };

    useEffect(() => {
        loadMembers();
    }, [application]);

    const saveRoleMembers = async () => {
        state.loading = true;
        let res = await graphqlFetch({
            query: FindOneRole,
            variables: { aiUuid: application.aiUuid, arName: roleKey },
        });
        let query = `mutation MyMutation {`;

        if (!res.a) {
            query += `a: createApplicationInnerBusinessRole(
                  input: {applicationInnerBusinessRole: {aiUuid: "${
                      application.aiUuid
                  }", arName: "${roleKey}", arCrti: "${new Date().getUTCTime()}", arRemk: "${role.text}"}}
                ) {
                  clientMutationId
                }`;
        }
        state.selectedMembers.map(
            (item, index) =>
                (query += ` ${"b" + index}:createApplicationInnerBusinessRolesMember(
                input: {applicationInnerBusinessRolesMember: {arName: "${roleKey}", aiUuid: "${application.aiUuid}", omUuid: "${item}"}}
              ) {
                clientMutationId
              }`)
        );
        query += `}`;
        res = await graphqlFetch({ query, variables: {} });
        if (res) {
            message.success("成功设置业务角色成员信息");
            await reloadData();
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    const levels = [];
    if (role.level) for (let i = 1; i <= role.level; i++) levels.push(i);

    return (
        <div style={{ padding: "0 30px" }}>
            <div style={{ marginBottom: 16 }}>
                <Checkbox.Group style={{ width: "100%" }} onChange={(checkedValues) => (state.selectedMembers = checkedValues)}>
                    <Row>
                        {state.members.map((item) => (
                            <Col span={6} key={item.omUuid}>
                                <Checkbox value={item.omUuid}>{item.orName}</Checkbox>
                            </Col>
                        ))}
                    </Row>
                </Checkbox.Group>
            </div>

            <Divider />
            <div style={{ textAlign: "center" }}>
                <Button theme="solid" disabled={state.selectedMembers.length === 0} onClick={saveRoleMembers}>
                    保存业务角色成员信息
                </Button>
            </div>
        </div>
    );
};

export default SetRoleMembers;
